/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.ove.palette.swing;

/**
 *
 * @author Mr.Sam
 */
import javax.swing.JTextField;
import fr.ove.palette.*;
import fr.ove.palette.events.*;

public class LinearEntry extends JTextField implements PaletteListener {
    /**
    * Consumes (i.e. treats) the event received.
    * @param paletteEvent the event to consume.
    */
    public void consumePaletteEvent(PaletteEvent paletteEvent) {
        int index;
        StringBuffer start, end;
        
        String text = getText();
        if (getSelectedText() == "") {
            index  = getCaretPosition();
            start = new StringBuffer(text.substring(0, index));
            end = new StringBuffer(text.substring(index));
        }
        else {
            index = getSelectionStart();
            start = new StringBuffer(text.substring(0, index));
            end = new StringBuffer(text.substring(getSelectionEnd()));
        }
        
        PaletteInfo paletteInfo = paletteEvent.getPaletteInfo();
        setText(start + paletteInfo.getSyntax() + end);
        setCaretPosition(index + paletteInfo.getOffset());
        requestFocus();
    }
}
